﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;
//using StoreClientModule;
using UnityCore;
using UploadManager;
using System.Drawing.Printing;

namespace MBBStoreClient
{
    public partial class frmStatementOfAccountViewer : Form
    {
        SynchronizeData sync = new SynchronizeData();
        UnityScriptEngine.Threader t = new UnityScriptEngine.Threader();

        readDetails path = new readDetails();
        readDetails pLD = new readDetails();
        priceDetails pD = new priceDetails();

        DataTable exportChargeInvoice = new DataTable();
        DataTable exportChargeInvoiceItem = new DataTable();
        DataTable exportChargePayments = new DataTable();
        DataTable exportSupplierProfile = new DataTable();

        DataTable extractedPO = new DataTable();

        DataRow[] chargeInvoices = new DataRow[0];
        DataRow[] resultInvoices = new DataRow[0];
        
        DataTable tmp = new DataTable();
        DataTable dt = new DataTable();
        DataTable result = new DataTable();

        double paymentGrandTotal = 0;

        public frmStatementOfAccountViewer()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }

        private void InitializeForm()
        {
            sync.ProcessCompleted += new CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new CoreHandler(sync_ProcessError);
            sync.Stores();

            path.fileNames = new List<string>();
            pD.tables = new List<DataTable>();
            btnSearch.Click += new EventHandler(btnSearch_Click);
            txtFilter.SelectedIndex = 0;
            cmbFilter02.SelectedIndex = 0;
            txtSearch.Focus();

            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            cmbStore.SelectedIndexChanged += new EventHandler(cmbStore_SelectedIndexChanged);
            t.MethodCompleted += new EventHandler(delegate(object sender, EventArgs e)
            {
                t.SafeCall(this, delegate
                {
                    switch (sender.ToString())
                    {
                        case "generateResult":
                            CreateDataTable();
                            if (cmbFilter02.Text.Equals("All"))
                            {
                                grdItems.DataSource = dt;
                                FormatGrid();
                                pnlMsg.Visible = false;
                            }
                            else
                            {
                                secondaryQuery();
                            }
                            
                            break;
                        case "generateFinalResult":
                            grdItems.DataSource = result;
                            FormatGrid();
                            pnlMsg.Visible = false;
                            break;
                    }
                });
            });
        }

        void cmbStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            //extract data
            txtSearch.Text = "";
            path.date = "";
            path.remNode = cmbStore.Text;
            path.fileNames.Clear();
            path.fileNames.Add("Charge Invoice");
            path.fileNames.Add("Charge Invoice Item");
            path.fileNames.Add("Charge Payments");

            path.fileNames.Add("tblsupplierprofile");
            sync.ReadMany(path);
            pnlMsg.Visible = true;
        }

        
        void btnSearch_Click(object sender, EventArgs e)
        {
            if (exportChargeInvoice.Rows.Count > 0)
            {
                pnlMsg.Visible = true;
                selectQuery();
            }
        }

        void secondaryQuery()
        {
            string fltr = cmbFilter02.Text;

            switch(fltr)
            {
                case "With Balance": resultInvoices = dt.Select("Balance <> '0.00'"); break;
                case "Fully Paid": resultInvoices = dt.Select("Balance = '0.00'");  break;
            }
            t.MethodCall(generateFinalResult);
        }

        void selectQuery()
        {
            string[] arr = txtDate.Text.Split('/');
            string month = arr[0];
            int m = int.Parse(month);
            string fltr = "", src = "";
            fltr = txtFilter.Text;
            src = txtSearch.Text;
            
                switch (fltr)
                {
                    case "All": chargeInvoices = exportChargeInvoice.Select("fSoldTo LIKE '%" + src + "%'");
                        break;
                    case "Year": chargeInvoices = exportChargeInvoice.Select("fSoldTo LIKE '%" + src + "%' AND fDate LIKE '%" + arr[1] + "'");
                        break;
                    case "Month": chargeInvoices = exportChargeInvoice.Select("fSoldTo LIKE '%" + src + "%' AND fDate LIKE '" + m.ToString() + "%'");
                        break;
                    case "MonthYear": chargeInvoices = exportChargeInvoice.Select("fSoldTo LIKE '%" + src + "%' AND ( fDate LIKE '" + arr[0] + "%' AND fDate LIKE '%" + arr[1] + "')");
                        break;
                }
                t.MethodCall(generateResult);
        }

        void generateFinalResult()
        {
            result = dt.Clone();
            for (int i = 0; i < resultInvoices.Length; i++)
                result.ImportRow(resultInvoices[i]);
        }

        void generateResult()
        {
            
            tmp = exportChargeInvoice.Clone();
            for (int i = 0; i < chargeInvoices.Length; i++)
                tmp.ImportRow(chargeInvoices[i]);
            
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
                pnlMsg.Visible = false;
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        cmbStore.SelectedIndex = 0;
                        //extract data
                        
                        break;
                    case "ReadMany":
                        exportChargeInvoice = sync.exportTables[0];
                        exportChargeInvoiceItem = sync.exportTables[1];
                        exportChargePayments = sync.exportTables[2];

                            autoAccountName();
                            pnlMsg.Visible = false;
                        break;
                }
            });
        }

        void autoAccountName()
        {
            if (exportChargeInvoice.Rows.Count > 0)
            {
                DataTable accountName = exportChargeInvoice.DefaultView.ToTable(true, "fSoldTo");
                string[] account = new string[accountName.Rows.Count];
                for (int i = 0; i < accountName.Rows.Count; i++)
                {
                    account[i] = accountName.Rows[i]["fSoldTo"].ToString();
                }

                txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
                txtSearch.AutoCompleteCustomSource.AddRange(account);
            }
        }
        string[] soldTo = new string[0];
        void CreateDataTable()
        {
            
            dt = new DataTable();
            dt.Columns.Add("Date");
            dt.Columns.Add("Charge Invoice Number");
            dt.Columns.Add("Total Amount");
            dt.Columns.Add("Total Payments");
            dt.Columns.Add("Balance");
            
            soldTo = new string[tmp.Rows.Count];

            for (int i = 0; i < tmp.Rows.Count; i++)
            {
                double chargeAmount = 0, totalPayment = 0;
                DataRow dr = dt.NewRow();
                dr["Date"] = tmp.Rows[i]["fDate"].ToString();
                dr["Charge Invoice Number"] = tmp.Rows[i]["fInvoice"].ToString();
                soldTo[i] = tmp.Rows[i]["fSoldTo"].ToString();

                string invoice = tmp.Rows[i]["fInvoice"].ToString();

                for (int j = 0; j < exportChargeInvoiceItem.Rows.Count; j++)
                {
                    string tmpInvoice = exportChargeInvoiceItem.Rows[j]["fInvoice"].ToString();
                    if(invoice.Equals(tmpInvoice))
                    {
                        double qty = double.Parse(exportChargeInvoiceItem.Rows[j]["fQty"].ToString());
                        double price = double.Parse(exportChargeInvoiceItem.Rows[j]["fUnitPrice"].ToString());
                        double amt = qty * price;
                        chargeAmount += amt;
                    }
                }
                dr["Total Amount"] = Common.FormatCurrency(chargeAmount);

                for (int j = 0; j < exportChargePayments.Rows.Count; j++)
                {
                    string tmpInvoice = exportChargePayments.Rows[j]["fInvoiceNumber"].ToString();
                    if (invoice.Equals(tmpInvoice))
                    {
                        double payment = double.Parse(exportChargePayments.Rows[j]["fAmount"].ToString());
                        totalPayment += payment;
                    }
                }

                double balance = chargeAmount - totalPayment;

                dr["Total Payments"] = Common.FormatCurrency(totalPayment);
                dr["Balance"] = Common.FormatCurrency(balance);
                dt.Rows.Add(dr);
            }
                
              //  return dt;
        }

        void FormatGrid()
        {
            grdItems.Columns[0].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 20) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 20) / 100;
           

            grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
           
            lblStatus.Text = grdItems.Rows.Count + " Records";
            grdItems.Sort(grdItems.Columns[0], ListSortDirection.Ascending);

        }

        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count > 0)
            {
                Common.parent.ViewChargedInvoice(grdItems.Rows[grdItems.SelectedRows[0].Index].Cells[1].Value.ToString(), cmbStore.Text);
            }
        }

        //printing
        int cnt = 0;
        int pp = 1;
        float tAmt = 0f;
        float tPay = 0f;
        float tBal = 0f;

        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                pp = 1;
                cnt = 0;
                tAmt = 0f;
                tPay = 0f;
                tBal = 0f;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 150;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Courier New", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(cmbStore.Text, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString(Common.lStoreAddress, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 70, sf);

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Charge Invoices Summary - Page " + pp, cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(DateTime.Now.ToString(), cFont, Brushes.Black, rm + 100, y, sf);
            //Column Header
            y += ht;
            y += ht;

            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm + 100, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm + 100, ht);
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 18) / 100);
            float tx = lm + (((rm - lm) * 9f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Date", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 25) / 100;
            tx = cx - ((rm - lm) * 25) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Charge Invoice", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 25) / 100;
            tx = cx - ((rm - lm) * 25) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 25) / 100;
            tx = cx - ((rm - lm) * 25) / 200;
            //e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            //e.Graphics.DrawString("Check No: ", cFont, Brushes.Black, tx, y, sf);
            // cx += ((rm - lm) * 18) / 100;
            //tx = cx - ((rm - lm) * 18) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Payments", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 25) / 100;
            e.Graphics.DrawString("Balance", cFont, Brushes.Black, tx, y, sf);
            //Data
            y += (ht * (1.5f)) * 2;
            cFont = new Font("Courier New", 10f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0;

            while (cl <= lpp && cnt < grdItems.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 1;
                string str = grdItems.Rows[cnt].Cells[0].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 21) / 100;
                str = grdItems.Rows[cnt].Cells[1].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                //For the sold To printing
                e.Graphics.DrawString(soldTo[cnt], cFont, Brushes.Black, stx, y - cFont.Height, sf);

                sf.Alignment = StringAlignment.Far;

                stx += ((rm - lm) * 43) / 100;
                str = grdItems.Rows[cnt].Cells[2].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                tAmt += float.Parse(str);

                stx += ((rm - lm) * 25) / 100;
                str = grdItems.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                tPay += float.Parse(str);

                stx += ((rm - lm) * 25) / 100;
                str = grdItems.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                tBal += float.Parse(str);

                y += (ht*2);
                cnt++;
                cl+=2;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdItems.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                pp = 1;
                e.HasMorePages = false;
                cnt = 0;

                stx = lm + 1;
                sf.Alignment = StringAlignment.Near;
                y += ht;
                e.Graphics.DrawString("Total Amount  : " + tAmt.ToString("#,#0.00"), cFont, Brushes.Black, stx, y, sf);

                y += ht;
                e.Graphics.DrawString("Total Payment : " + tPay.ToString("#,#0.00"), cFont, Brushes.Black, stx, y, sf);

                y += ht;
                e.Graphics.DrawString("Total Balance : " + tBal.ToString("#,#0.00"), cFont, Brushes.Black, stx, y, sf);

                tAmt = 0f;
                tPay = 0f;
                tBal = 0f;

            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}
